home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4178 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.3 KB  |  47 lines

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: novice question on copy constru
  5. Date: Sun, 28 Jan 1996 13:14:14 GMT
  6. Organization: Netcom
  7. Message-ID: <310b743f.135769536@nntp.ix.netcom.com>
  8. References: <4efpie$jsq@news.ust.hk>
  9. NNTP-Posting-Host: ix-dc7-18.ix.netcom.com
  10. X-NETCOM-Date: Sun Jan 28  5:13:57 AM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. ee_ckmaa@uxmail.ust.hk (Chan Ka Ming) wrote:
  14.  
  15. > I don't understand why one should create a copy constructor. Doesn't the
  16. > computer will do the job for you when pass arguments by value? Thanks
  17.  
  18. The compiler will supply a copy constructor, but in many cases in will
  19. not do so correctly.  Consider
  20.  
  21.     class A {
  22.       private:
  23.         char* str;
  24.       public:
  25.         A(const char* s) : str(new char[strlen(s) + 1])
  26.         { strcpy(str, s); }
  27.         ~A() { delete[] str; }
  28.     }
  29.  
  30.     void f(A);
  31.  
  32.     void g()
  33.     {
  34.       A a;
  35.       f(a);
  36.       // ...
  37.     }
  38.  
  39. The default copy constructor does a memberwise copy.  The copy of a
  40. that is sent to f will contain a pointer to the same string as the
  41. original a.  When it is destroyed, the string will be deleted, but a
  42. is still active.  When a is later destroyed, the string will be
  43. deleted again.  Nothing good happens when you delete an object twice.
  44.  
  45.  
  46. Michael M Rubenstein
  47.